package bepeb.views;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public class OpenTypeAction implements IObjectActionDelegate {
	
	private String className;

	private IWorkbenchPart view;

	public OpenTypeAction() {
	}
	
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		this.view = targetPart;
		
	}

	public void run(IAction action) {
		if (className == null) {
			return;
		}

		Utils.openType(view.getSite().getShell(), className);
	}

	public void selectionChanged(IAction action, ISelection selection) {
		className = null;
		action.setEnabled(false);
		if (selection instanceof ITreeSelection) {
			ITreeSelection treeSelection = (ITreeSelection) selection;
			TreePath[] paths = treeSelection.getPaths();
			if (paths.length > 0) {
				Object lastSegment = paths[0].getLastSegment();
				if (lastSegment instanceof Attribute) {
					Attribute attribute = ((Attribute) lastSegment);
					String classNameString = attribute.getValue();
					if (classNameString != null) {
						int indexOfequals = classNameString.indexOf('=');
						if (indexOfequals != -1) {
							classNameString = classNameString.substring(indexOfequals + 2);
						}
						if (Utils.isJavaTypeName(classNameString)) {
							className = classNameString;
							action.setEnabled(true);
						}
					}
				}
			}
		}		
	}
}
